<?php /**
 * Created by 深圳市丹宏昊天电子商务有限公司.
 * 作 者: sqingwen
 * 日 期: 2017/3/17
 *
 */
?>
<link rel="stylesheet" type="text/css" href="<?= base_url() . 'resource/jeasyui/themes/metro/easyui.css' ?>"/>
<script type="text/javascript">
    //合并单元格的代码 begin
    $.extend($.fn.datagrid.methods, {
        autoMergeCells: function (jq, fields) {
            return jq.each(function () {
                var target = $(this);
                if (!fields) {
                    fields = target.datagrid("getColumnFields");
                }
                var rows = target.datagrid("getRows");
                var i = 0,
                    j = 0,
                    temp = {};
                for (i; i < rows.length; i++) {
                    var row = rows[i];
                    j = 0;
                    for (j; j < fields.length; j++) {
                        var field = fields[j];
                        var tf = temp[field];
                        if (!tf) {
                            tf = temp[field] = {};
                            tf[row[field]] = [i];
                        } else {
                            var tfv = tf[row[field]];
                            if (tfv) {
                                tfv.push(i);
                            } else {
                                tfv = tf[row[field]] = [i];
                            }
                        }
                    }
                }
                $.each(temp,
                    function (field, colunm) {
                        $.each(colunm,
                            function () {
                                var group = this;

                                if (group.length > 1) {
                                    var before, after, megerIndex = group[0];
                                    for (var i = 0; i < group.length; i++) {
                                        before = group[i];
                                        after = group[i + 1];
                                        if (after && (after - before) == 1) {
                                            continue;
                                        }
                                        var rowspan = before - megerIndex + 1;
                                        if (rowspan > 1) {
                                            target.datagrid('mergeCells', {
                                                index: megerIndex,
                                                field: field,
                                                rowspan: rowspan
                                            });
                                        }
                                        if (after && (after - before) != 1) {
                                            megerIndex = after;
                                        }
                                    }
                                }
                            });
                    });
            });
        }
    });
    //合并单元格的代码 end
    var shipTypes = [
        {id: '1', name: 'DHL'},
        {id: '2', name: 'UPS'}
    ];
    var pickupCountries = [
        {id: "CN", name: 'CN'},
        {id: "DE", name: 'DE'},
        {id: "US", name: 'US'},
        {id: "ES", name: 'ES'},
        {id: "IT", name: 'IT'},
        {id: "FR", name: 'FR'},
        {id: "RU", name: 'RU'}
    ];
    var categories = [
        <?php foreach ($categories as $k => $v): ?>
        {id: "<?= $v['id'] ?>", name: '<?= $v['name'] ?>'},
        <?php endforeach; ?>
    ];

    $(function () {
        $('#tt').datagrid({
            title: '自定义费用',
            pagination: true, //表示在datagrid设置分页
            singleSelect: true,
            border: false,
            striped: false,
            fitColumns: true,
            collapsible: false,
            idField: 'id',
            sortOrder: "desc",

            url: '/sc/users/Shipping/ajaxLoadCustomizePrice',
            columns: [[

              {
                    field: 'category_id',
                    title: '产品分类',
                    align: 'left',

                    formatter: function (value) {
                        for (var i = 0; i < categories.length; i++) {
                            if (categories[i].id == value)
                                return categories[i].name;
                        }
                        return value;
                    },

                },


                {
                    field: 'brand_name',
                    title: '产品品牌',
                    align: 'right',
                    width: fixWidth(0.05),

                },
                {
                    field: 'model_name',
                    title: '产品型号',
                    align: 'right',
                    width: fixWidth(0.05),


                }
                ,
                {
                    field: 'delivery_fee',
                    title: '价格',
                    align: 'right',
                    width: fixWidth(0.05),
                    editor: {
                        type: 'numberbox', options: {
                            precision: 2, required: true
                        }
                    }
                }
                ,
                {
                    field: 'delivery_cost_fee',
                    title: '预计成本',
                    align: 'right',
                    width: fixWidth(0.05),
                    editor: {
                        type: 'numberbox', options: {
                            precision: 2, required: true
                        }
                    }
                }
                ,
                {
                    field: 'pickup_country', title: '发货地',
                    width: fixWidth(0.05),
                    align: 'left',
                    formatter: function (value) {
                        for (var i = 0; i < pickupCountries.length; i++) {
                            if (pickupCountries[i].id == value)
                                return pickupCountries[i].id;
                        }
                        return value;
                    }

                    ,
                    editor: {
                        type: 'combobox',
                        options: {
                            valueField: 'id',
                            textField: 'name',
                            data: pickupCountries,
                            required: true
                        }
                    }
                }
                ,
                {
                    field: 'delivery_country', title: '目的地',
                    width: fixWidth(0.2),
                    align: 'left',
                    formatter: function (value) {
                        return '[' + value + ']';
                    },
                    editor: {
                        type: 'combotree',
                        options: {
                            url: '/sc/users/shipping/ajaxLoadCountryItem',
                            multiple: true,
                            onCheck: function (record) {
                                test(record);
                            },
                            required: true

                        }
                    }
                }
                ,
                {
                    field: 'product_weight',
                    title: '产品重量（g）',
                    align: 'right',
                    editor: {
                        type: 'numberbox', options: {
                            precision: 2, required: true
                        }
                    }

                }
                ,
                {
                    field: 'shipping_type', title: '物流渠道',
                    formatter: function (value) {
                        for (var i = 0; i < shipTypes.length; i++) {
                            if (shipTypes[i].id == value)
                                return shipTypes[i].name;
                        }
                        return value;
                    }
                    ,
                    editor: {
                        type: 'combobox',
                        options: {
                            valueField: 'id',
                            textField: 'name',
                            data: shipTypes,
                            required: true
                        }
                    }
                }
                ,
                {
                    field: 'action', title: 'Action', align: 'center',
                    formatter: function (value, row, index) {

                        if (row.editing) {
                            var s = '<a href="#" onclick="saverow(this)">Save</a> ';
                            var c = '<a href="#" onclick="cancelrow(this)">Cancel</a>';
                            return s + c;
                        } else {
                            var e = '<a href="#" onclick="editrow(this)">Edit</a> ';
                            var d = '<a href="#" onclick="deleterow(this,\'' + row.id + '\')">Delete</a> ';

                            return e + d;
                        }
                    }
                }
            ]],
            onEndEdit: function (index, row) {
                var ed = $(this).datagrid('getEditor', {
                    index: index,
                    field: 'id'
                });
                //row.productname = $(ed.target).combobox('getText');
            }
            ,
            onBeforeEdit: function (index, row) {
                row.editing = true;
                $(this).datagrid('refreshRow', index);
            }
            ,
            onAfterEdit: function (index, row) {
                row.editing = false;
                $(this).datagrid('reload');
            }
            ,
            onCancelEdit: function (index, row) {
                row.editing = false;
                $(this).datagrid('reload');
            }, onLoadSuccess: function (data) {
                //所有列进行合并操作
                //$(this).datagrid("autoMergeCells");
                //指定列进行合并操作
                //$(this).datagrid("autoMergeCells");


            }

        });
    });
    //


    function getRowIndex(target) {
        var tr = $(target).closest('tr.datagrid-row');
        return parseInt(tr.attr('datagrid-row-index'));
    }
    function editrow(target) {
        $('#tt').datagrid('beginEdit', getRowIndex(target));

    }
    function deleterow(target, id) {

        $.messager.confirm('Confirm', 'Are you sure?', function (r) {
            if (r) {
                $.post('/sc/users/Shipping/ajaxDelShippingCustomize', {'id': id}, function (data) {
                    if (data == 1) {
                        $('#tt').datagrid('deleteRow', getRowIndex(target));
                        $.messager.alert('Success', 'Delete Success!');
                    }
                }, 'text');

            }
        });
    }
    function saverow(target) {
        $('#tt').datagrid('endEdit', getRowIndex(target));
        var row = $('#tt').datagrid('getSelected');
        if (row) {
            $.post('/sc/users/Shipping/ajaxAddShippingCustomize', {'data': JSON.stringify(row)}, function (data) {
                $.messager.alert('Success', 'Edit Success!');
                $('#tt').datagrid('reload');
            }, 'text');
        }

    }
    function cancelrow(target) {
        $('#tt').datagrid('cancelEdit', getRowIndex(target));
    }
    function insert() {
        var row = $('#tt').datagrid('getSelected');
        var e = $("#tt").datagrid('getColumnOption', 'model_name');
        e.editor = {
            type: 'combobox',
            options: {
                url: '/sc/users/Shipping/ajaxLoadModel?cid=1',
                valueField: 'id',
                textField: 'name',
                required: true

            }
        }

        var eb = $("#tt").datagrid('getColumnOption', 'brand_name');
        eb.editor = {
            type: 'combobox',
            options: {
                url: '/sc/users/Shipping/ajaxLoadBrand?cid=1',
                valueField: 'id',
                textField: 'name',
                required: true,
                onSelect: function (data) {
                    var row = $('#tt').datagrid('getSelected');
                    var rowIndex = $('#tt').datagrid('getRowIndex', row);//获取行号
                    var thisTarget = $('#tt').datagrid('getEditor', {
                        'index': rowIndex,
                        'field': 'category_id'
                    }).target;
                    var value = thisTarget.combobox('getValue');

                    var target = $('#tt').datagrid('getEditor', {'index': rowIndex, 'field': 'model_name'}).target;
                    target.combobox('clear'); //清除原来的数据
                    var url = '/sc/users/Shipping/ajaxLoadModel?bid=' + data.id + '&cid=' + value;
                    target.combobox('reload', url);//联动下拉列表重载

                }
            }
        }

        var ec = $("#tt").datagrid('getColumnOption', 'category_id');
        ec.editor = {
            type: 'combobox',
            options: {
                valueField: 'id',
                textField: 'name',
                data: categories,
                required: true,
                onSelect: function (data) {
                    var row = $('#tt').datagrid('getSelected');
                    var rowIndex = $('#tt').datagrid('getRowIndex', row);//获取行号
                    var value = data.id;
                    var target = $('#tt').datagrid('getEditor', {'index': rowIndex, 'field': 'brand_name'}).target;
                    target.combobox('clear'); //清除原来的数据

                    $('#tt').datagrid('getEditor', {'index': rowIndex, 'field': 'model_name'}).target.combobox('clear');
                    var url = '/sc/users/Shipping/ajaxLoadBrand?cid=' + value;
                    target.combobox('reload', url);//联动下拉列表重载
                }
            }
        }
        var ec = $("#tt").datagrid('getColumnOption', 'model_name');
        ec.editor = {
            type: 'combobox',
            options: {
                valueField: 'id',
                textField: 'name',
                data: categories,
                required: true,
                onSelect: function (data) {
                    var row = $('#tt').datagrid('getSelected');
                    var rowIndex = $('#tt').datagrid('getRowIndex', row);//获取行号
                    var value = data.mid;
                    $.post('/sc/users/Shipping/ajaxLoadModelWeight', {'id': value}, function (dat) {
                        var target = $('#tt').datagrid('getEditor', {
                            'index': rowIndex,
                            'field': 'product_weight'
                        }).target;
                        target.numberbox('setValue', dat); //清除原来的数据
                    }, 'text')


                }
            }
        }


        index = 0;//默认为索引0 的插入行
        $('#tt').datagrid('insertRow', {
            index: 0,
            row: {'type': 'add'}
        });
        $('#tt').datagrid('selectRow', index);
        $('#tt').datagrid('beginEdit', index);
    }


    $(function () {
        $(window).resize(function () {
            $('#tt').datagrid('resize', {
                width: $(window).width() - 10,
                height: $(window).height() - 35
            }).datagrid('resize', {
                width: $(window).width() - 10,
                height: $(window).height() - 35
            });
        });
    });
    function fixHeight(percent) {
        return (document.body.clientHeight) * percent;
    }

    function fixWidth(percent) {
        return (document.body.clientWidth - 5) * percent;
    }


    function test(record) {
        var rowIdx = $('#tt').datagrid('getRowIndex', $('#tt').datagrid('getSelected'));
        console.log(record);

        //要不是在grid中我可以直接通过$('#treeObj').combotree('tree').tree('getParent',record.target)
        //但是这里无法通过这个写法获得树对象！ 根据
    }

    function addShiprow(id) {
        $('#ddShip').dialog('open');
        $('#txtCusId').val(id);
    }

</script>
<style type="text/css">
    .datagrid-row-over, .datagrid-row-selected {
        background: none;
    }

    .datagrid-row-selected td {
        background-color: #CCE6FF
    }

    .datagrid-row-selected > .datagrid-td-merged, .datagrid-row-selected > td:first-child {
        background: none;
    }

    .datagrid-view {
        　　height: 98px;
    }

</style>


<!--菜单 start-->
<?php $this->load->view('defaults/common/left');?>
<!--菜单 end-->
<div id="content">
    <div class="page-header">
        <div class="container-fluid">
          <h1>自定义运费管理</h1>
          <?=$this->breadcrumb->generateHTML();?>
        </div>
    </div>
    <div class="container-fluid">
        <div class="panel panel-default">
          <div class="panel-body">
            <div id="p" class="easyui-panel" title="" style="width:100%;padding:10px;">
                <table style="width:99%;">
                    <tr>
                        <td>
                            <!--条件查询 -->
                            <div data-options="region:'north',split:false,border:false,title:'查询条件',collapsed:false,iconCls:'icon-search'">

                                产品型号:<input type="text" name="dtTplname" id="dtTplname"
                                            class="easyui-validatebox"
                                            maxlength="10" style="width:150px;height: 28px"/>

                                &nbsp;&nbsp;<a href="javascript:void(0)" class="easyui-linkbutton"
                                               data-options="iconCls:'icon-search'" onclick="Search()">查询</a>
                            </div>
                            <div style="clear: both;margin-top:10px;margin-bottom:20px;">
                                运费试算:
                                <select style="width:100px;height: 30px">
                                    <option>按重量</option>
                                    <option>按产品</option>
                                </select>

                                重量:<input type="text" style="width:50px;height: 26px" id="ctBeginWeight"
                                          name="ctBeginWeight"> - <input type="text"
                                                                         style="width:50px;height: 26px"
                                                                         id="ctEndWeight"
                                                                         name="ctEndWeight">
                                KG
                                &nbsp;&nbsp;发件国家： <select style="width:100px;height: 28px" id="ctFromCountry"
                                                          name="ctFromCountry">
                                    <option value="DE">德国</option>
                                    <option value="US">美国</option>
                                    <option value="UK">英国</option>

                                </select>
                                &nbsp;&nbsp;收件国家：
                                <input id="ctToCountry" class="easyui-combobox" name="ctToCountry"
                                       style="width:80px;height: 28px;"
                                       data-options="valueField:'id',textField:'text',url:'/sc/users/shipping/ajaxLoadCountryItem'">
                                &nbsp;<a href="javascript:void(0)" class="easyui-linkbutton btnCntPrice"
                                         onclick="javascript:cntPrice()">获取运费</a>


                                &nbsp;&nbsp;&nbsp;&nbsp;

                                <a href="#" class="easyui-linkbutton" onclick="insert()">添加</a>
                            </div>
                        </td>
                    </tr>

                    <tr>
                        <td>
                            <table id="tt">

                            </table>

                        </td>
                    </tr>
                </table>


            </div>
          </div>
        </div>
    </div>
    
  <!-- 弹出层 begin -->
    <div id="ddShip" class="easyui-dialog" title="Trial Price" style="width:450px;height:150px;padding:10px 5px;"
         data-options="iconCls:'icon-save',resizable:true,closed:true">
        <table id="dtTrialPrice" style="width:100%;heigth:130px;">

        </table>

    </div>
    <!-- 弹出层 end -->

    <script type="text/javascript">
        cntPrice = function () {
            var ctBeginWeight = $('#ctBeginWeight').val();
            var ctEndWeight = $('#ctEndWeight').val();
            var ctFromCountry = $('#ctFromCountry').val();
            var ctToCountry = $('#ctToCountry').combobox("getValue");

            if (($.trim(ctBeginWeight).length) < 1 || ($.trim(ctEndWeight).length) < 1 || ($.trim(ctFromCountry).length) < 1 || ($.trim(ctToCountry).length) < 1) {
                $.messager.alert("Notice", "the data you entered is incomplete  !");
                return false;
            }

            $('#ddShip').dialog('open');
            //设置位置
            alert($('.btnCntPrice').offset().top);
            //$('#ddShip).panel('move',{top:$('.btnCntPrice').offset().top});
            $('#dtTrialPrice').datagrid({
                fitColumns: true,
                url: '/sc/users/Shipping/ajaxGetTrialPrice',
                queryParams: {
                    'ctBeginWeight': ctBeginWeight,
                    'ctEndWeight': ctEndWeight,
                    'ctFromCountry': ctFromCountry,
                    'ctToCountry': ctToCountry
                },
                columns: [[
                    {field: 'tpl_name', title: 'Name', width: 60},
                    {field: 'pickup_country', title: 'From', width: 50},
                    {field: 'delivery_country', title: 'To', width: 90},
                    {field: 'begin_weight', title: 'Minimum', width: 60},
                    {field: 'end_weight', title: 'Max', width: 60},
                    {field: 'delivery_fee', title: 'Price', width: 60},
                    {field: 'delivery_cost_fee', title: 'Cost Price', width: 80}
                ]],

            });

            //console.log(ctBeginWeight + '___' + ctEndWeight + '___' + ctFromCountry + '___' + ctToCountry);

        }
    </script>

</div>
